
package com.sailing.lianxi.util.thread;

public class ThreadTool {

    /**
     * 
     * findThreadById[根据线程id获取线程]
     * 创建人:  wanggang
     * 创建时间: 2018年6月25日 下午2:15:34
     *
     * @Title: findThreadById
     * @param threadId 线程id
     * @return
     * @since  CodingExample　Ver(编码范例查看) 1.1
     */
    public static Thread findThreadById(long threadId){
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        while(null!=group){
            Thread[] threads = new Thread[(int)(group.activeCount()*1.2)];
            int count = group.enumerate(threads,true);
            for(int i=0;i<count;i++){
                if(threadId==threads[i].getId()){
                    return threads[i];
                }
            }
            group = group.getParent();
        }
        return null;
    }
    
    
    /**
     * 
     * findThreadByName[根据线程名称获取线程对象]
     * 创建人:  wanggang
     * 创建时间: 2018年6月25日 下午2:22:49
     *
     * @Title: findThreadByName
     * @param threadName 线程名称
     * @return
     * @since  CodingExample　Ver(编码范例查看) 1.1
     */
    public static Thread findThreadByName(String threadName){
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        while(null!=group){
            Thread[] threads = new Thread[(int)(group.activeCount()*1.2)];
            int count = group.enumerate(threads,true);
            for(int i=0;i<count;i++){
                if(threadName.equals(threads[i].getName())){
                    return threads[i];
                }
            }
            group = group.getParent();
        }
        return null;
    }
    
    public static Thread[] findAllThread(){
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        ThreadGroup topGroup = group;
     
        /* 遍历线程组树，获取根线程组 */
        while ( group != null )
        {
            System.out.println("111");
            topGroup    = group;
            group        = group.getParent();
        }
        /* 激活的线程数加倍 */
        int estimatedSize = topGroup.activeCount() * 2;
        Thread[] slackList = new Thread[estimatedSize];
     
        /* 获取根线程组的所有线程 */
        int actualSize = topGroup.enumerate( slackList );
        /* copy into a list that is the exact size */
        Thread[] list = new Thread[actualSize];
        System.arraycopy( slackList, 0, list, 0, actualSize );
        return (list);
    }
}

